<template>
  <el-dialog
    :title="title"
    :visible="isShow"
    width="400px"
    destroy-on-close
    @close="isShow = false"
  >
    <el-autocomplete
      v-model="state"
      popper-class="my-autocomplete"
      :fetch-suggestions="querySearch"
      :trigger-on-focus="false"
      placeholder="搜索文件"
      style="width: 300px"
      @select="handleSelect"
    >
      <i slot="suffix" class="el-icon-search el-input__icon" />
      <template slot-scope="{ item }">
        <div class="dis-flex">
          <div class="icon-search-file icon-style" />
          <div class="name">{{ item.value }}</div>
        </div>
      </template>
    </el-autocomplete>
  </el-dialog>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      restaurants: [],
      state: '',
      isShow: false
    };
  },
  methods: {
    show() {
      this.isShow = true;
      this.restaurants = [];
      this.getFile(this.$store.state.matlab.originTreeData);
    },
    hide() {
      this.isShow = false;
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    handleSelect(item) {
      this.$store.dispatch('matlab/getFile', item.data);
      this.hide();
    },
    getFile(data) {
      data.map((item) => {
        if (item.isFile) {
          this.restaurants.push({
            value: `${item.path}/${item.label}`,
            data: item
          });
        } else {
          if (item.children.length) {
            this.getFile(item.children);
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.icon-style {
  width: 16px;
  height: 16px;
  margin-top: 9px;
  margin-right: 5px;
}
.my-autocomplete {
  width: 300px;

  li {
    line-height: normal;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}
</style>
